﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PSE.Tools.SchemaComparer.Comparer;
using System.IO;
using System.Diagnostics;
using System.Reflection;

//TODO: Adicionar um GRID spliter no painel de apresentacao
namespace PSE.Tools.SchemaComparer.WindowsApp
{
    /// <summary>
    /// Interaction logic for UcPropertyCompareResultItem.xaml
    /// </summary>
    public partial class UcPropertyCompareResultItem : UserControl
    {
        private Configurations _config;

        public string SourceSchemaName
        {
            get { return (string)GetValue(SourceSchemaNameProperty); }
            set { SetValue(SourceSchemaNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SourceSchemaName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceSchemaNameProperty =
            DependencyProperty.Register("SourceSchemaName", typeof(string), typeof(UcPropertyCompareResultItem), new UIPropertyMetadata(string.Empty));


        public string SourceValue
        {
            get { return (string)GetValue(SourceValueProperty); }
            set { SetValue(SourceValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SourceValue.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceValueProperty =
            DependencyProperty.Register("SourceValue", typeof(string), typeof(UcPropertyCompareResultItem), new UIPropertyMetadata(string.Empty));


        public string TargetSchemaName
        {
            get { return (string)GetValue(TargetSchemaNameProperty); }
            set { SetValue(TargetSchemaNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TargetSchemaName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetSchemaNameProperty =
            DependencyProperty.Register("TargetSchemaName", typeof(string), typeof(UcPropertyCompareResultItem), new UIPropertyMetadata(string.Empty));


        public Window ParentWindow
        {
            get;
            set;
        }

        public string TargetValue
        {
            get { return (string)GetValue(TargetValueProperty); }
            set { SetValue(TargetValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TargetValue.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TargetValueProperty =
            DependencyProperty.Register("TargetValue", typeof(string), typeof(UcPropertyCompareResultItem), new UIPropertyMetadata(string.Empty));

        private string _targetValue;
        private string _sourceValue;

        public UcPropertyCompareResultItem(Window parentWindow, Configurations config, string sourceSchemaName, string sourceValue, string targetSchemaName, string targetValue)
        {
            InitializeComponent();

            ParentWindow = parentWindow;

            _config = config;

            CheckExternalCompareTool();

            this.DataContext = this;
            this.SourceSchemaName = sourceSchemaName;

            _sourceValue = sourceValue;
            if (_sourceValue == null)
                _sourceValue = "NULL";

            this.SourceValue = _sourceValue.Length >= 50 ? "Clique no botão ao lado para visualizar" : "[" + _sourceValue + "]";


            this.TargetSchemaName = targetSchemaName;
            _targetValue = targetValue;
            if (_targetValue == null)
                _targetValue = "NULL";

            this.TargetValue = _targetValue.Length >= 50 ? "Clique no botão ao lado para visualizar" : "[" + _targetValue + "]";

        }

        private void CheckExternalCompareTool()
        {
            string absPath = _config.ComparerToolAbsolutePath;
            if (string.IsNullOrEmpty(absPath))
                btnShowValueCompareTool.IsEnabled = false;
            else
            {
                if (File.Exists(absPath))
                    btnShowValueCompareTool.IsEnabled = true;
            }
        }

        private void btnShowValue_Click(object sender, RoutedEventArgs e)
        {
            ValuesView vv = new ValuesView(this.SourceSchemaName, this._sourceValue, this.TargetSchemaName, this._targetValue);
            vv.Owner = ParentWindow;
            vv.ShowDialog();
        }

        private void btnShowValueCompareTool_Click(object sender, RoutedEventArgs e)
        {
            string absPath = _config.ComparerToolAbsolutePath;
            if (!File.Exists(absPath))
                MessageBox.Show("Não foi possível encontrar a ferramenta externa de comparação no caminho configurado. Por favor verifique as configurações da aplicação");
            else
            {

                string tempDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\temp\";

                //gerar os arquivos temporarios utilizados pela ferramenta de comparacao
                if (!Directory.Exists(tempDir))
                    Directory.CreateDirectory(tempDir);

                string sourceFileName, targetFileName;
                DateTime now = DateTime.Now;

                sourceFileName = tempDir + this.SourceSchemaName + now.ToString("HHmmssms") + ".cmp";
                targetFileName = tempDir + this.TargetSchemaName + now.ToString("HHmmssms") + ".cmp";

                File.WriteAllText(sourceFileName, this._sourceValue);
                File.WriteAllText(targetFileName, this._targetValue);
                //abrir a ferramenta de comparacao

                Process p = new Process();
                // Redirect the output stream of the child process. 
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.FileName = absPath;
                p.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"", sourceFileName, targetFileName);
                p.Start();
                // Read the output stream first and then wait. 
                //string output = p.StandardOutput.ReadToEnd(); 
                p.WaitForExit();

                File.Delete(sourceFileName);
                File.Delete(targetFileName);
            }
        }
    }
}
